package com.ludaxu.zhbj.base;

import java.util.ArrayList;

import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.ludaxu.zhbj.NewsDetailActivity;
import com.ludaxu.zhbj.R;
import com.ludaxu.zhbj.domain.NewsData.NewsTabsData;
import com.ludaxu.zhbj.domain.TabData;
import com.ludaxu.zhbj.domain.TabData.TabNewsData;
import com.ludaxu.zhbj.domain.TabData.TopNewsData;
import com.ludaxu.zhbj.global.GlobalContants;
import com.ludaxu.zhbj.utils.PrefUtils;
import com.ludaxu.zhbj.view.RefreshListView;
import com.ludaxu.zhbj.view.RefreshListView.OnRefreshListener;
import com.viewpagerindicator.CirclePageIndicator;

import android.R.color;
import android.R.raw;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 页签详情页
 * 
 * @author ludaxu
 * 
 */
public class TabDetailPager extends BaseMenuDetailPager implements
		OnPageChangeListener {
	NewsTabsData mTabsData;
	private TextView tvText;
	private String mUrl;
	private TabData mTabDetailData;
	@ViewInject(R.id.vp_news)
	private ViewPager mViewPager;
	@ViewInject(R.id.tv_title)
	private TextView tvTitle;
	@ViewInject(R.id.indicator)
	private CirclePageIndicator mIndicator;// 头条新闻位置指示器

	private ArrayList<TopNewsData> mTopNewsList;// 头条新闻数据集合
	@ViewInject(R.id.lv_list)
	private RefreshListView lvList;// 新闻列表
	private ArrayList<TabNewsData> mNewsList;// 新闻列表数据集合
	private NewsAdapter mNewsAdapter;
	private String mMoreUrl;// 更多页面的地址
	private Handler mHandler;

	public TabDetailPager(Activity activity, NewsTabsData newsTabsData) {
		super(activity);
		mTabsData = newsTabsData;
		mUrl = GlobalContants.SERVICE_URL + mTabsData.url;
	}

	@Override
	public View initViews() {
		View view = View.inflate(mActivity, R.layout.tab_detail_pager, null);
		// 加载头布局
		View headerView = View.inflate(mActivity, R.layout.list_header_topnews,
				null);

		ViewUtils.inject(this, view);
		ViewUtils.inject(this, headerView);
		// listview添加头布局,那么,头布局就是listview的一部分
		lvList.addHeaderView(headerView);
		// 设置下拉刷新监听
		lvList.setOnReFreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				getDataFromServer();

			}

			@Override
			public void onLoadMore() {
				if (mMoreUrl != null) {
					getMoreDataFromServer();
				} else {
					Toast.makeText(mActivity, "最后一页了", 0).show();
					lvList.OnRefreshComplete();// 手气较布局加载更多的布局
				}

			}
		});

		lvList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				System.out.println("被点击:" + position);
				// 35311,34221,34234
				String ids = PrefUtils.getString(mActivity, "read_ids", "");
				if (!ids.contains(mNewsList.get(position).id)) {
					ids = ids + mNewsList.get(position).id + ",";
					PrefUtils.setString(mActivity, "read_ids", ids);
				}

				// mNewsAdapter.notifyDataSetChanged();
				// 局部界面刷新,这个view就是被点击的item布局对象
				changReadStatus(view);
				// 跳转到新闻详情页
				Intent intent = new Intent();
				intent.setClass(mActivity, NewsDetailActivity.class);
				intent.putExtra("url", mNewsList.get(position).url);
				mActivity.startActivity(intent);

			}
		});

		return view;
	}

	/**
	 * 改变已读的状态
	 */
	private void changReadStatus(View view) {
		TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
		tvTitle.setTextColor(Color.RED);

	}

	/**
	 * 加载下一页数据
	 */
	private void getMoreDataFromServer() {
		HttpUtils utils = new HttpUtils();
		utils.send(HttpMethod.GET, mMoreUrl, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String result = responseInfo.result;
				System.out.println("页签详情页返回结果");
				parseData(result, true);
				lvList.OnRefreshComplete();
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				Toast.makeText(mActivity, "页签详情页获取数据失败!", 0).show();
				lvList.OnRefreshComplete();
			}
		});
	}

	@Override
	public void initData() {
		getDataFromServer();
	}

	private void getDataFromServer() {
		HttpUtils utils = new HttpUtils();
		utils.send(HttpMethod.GET, mUrl, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String result = responseInfo.result;
				System.out.println("页签详情页返回结果");
				parseData(result, false);
				lvList.OnRefreshComplete();
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				Toast.makeText(mActivity, "页签详情页获取数据失败!", 0).show();
				lvList.OnRefreshComplete();
			}
		});
	}

	protected void parseData(String result, boolean isMore) {
		Gson gson = new Gson();
		mTabDetailData = gson.fromJson(result, TabData.class);
		System.out.println("页签详情页解析:" + mTabDetailData);
		// 处理一下链接
		String more = mTabDetailData.data.more;
		if (!TextUtils.isEmpty(more)) {
			mMoreUrl = GlobalContants.SERVICE_URL + more;

		} else {
			mMoreUrl = null;
		}
		if (!isMore) {

			mTopNewsList = mTabDetailData.data.topnews;
			mNewsList = mTabDetailData.data.news;

			if (mTopNewsList != null) {
				mViewPager.setAdapter(new TopNewsAdapter());
				mIndicator.setViewPager(mViewPager);
				mIndicator.setSnap(true);// 支持快照显示
				mIndicator.setOnPageChangeListener(this);
				mIndicator.onPageSelected(0);// 让指示器重新定位到第一个点
				tvTitle.setText(mTopNewsList.get(0).title);

			}
			// 自动轮播条显示
			if (mHandler == null) {
				mHandler = new Handler() {
					@Override
					public void handleMessage(Message msg) {
						int currentItem = mViewPager.getCurrentItem();
						if (currentItem < mTopNewsList.size() - 1) {
							currentItem++;
						} else {
							currentItem = 0;
						}
						mViewPager.setCurrentItem(currentItem);
						// 等切换后,又等3秒钟发一个消息
						mHandler.sendEmptyMessageDelayed(0, 3000);
					}
				};
				// 延时3秒钟发消息
				mHandler.sendEmptyMessageDelayed(0, 3000);
			}

			// 填充新闻列表
			if (mNewsList != null) {
				mNewsAdapter = new NewsAdapter();
				lvList.setAdapter(mNewsAdapter);
			}
		} else {// 如果是加载下一页,需要将数据追加给原来的集合
			ArrayList<TabNewsData> news = mTabDetailData.data.news;
			mNewsList.addAll(news);
			mNewsAdapter.notifyDataSetChanged();
		}

	}

	/**
	 * 头条新闻适配器
	 * 
	 * @author Administrator
	 * 
	 */
	class TopNewsAdapter extends PagerAdapter {

		private BitmapUtils utils;

		public TopNewsAdapter() {
			utils = new BitmapUtils(mActivity);
			// 在没有下载完成之前,所展示的默认图片
			utils.configDefaultLoadingImage(R.drawable.topnews_item_default);
		}

		@Override
		public int getCount() {
			return mTabDetailData.data.topnews.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// TODO Auto-generated method stub
			return arg0 == arg1;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			ImageView image = new ImageView(mActivity);
			// 父控件有多大,图片就显示多大
			image.setScaleType(ScaleType.FIT_XY);
			TopNewsData topNewsData = mTopNewsList.get(position);
			utils.display(image, topNewsData.topimage);// 传递imageView对象和图片地址

			container.addView(image);
			image.setOnTouchListener(new TopNewsTouchListener());
			return image;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

	}

	/**
	 * 头条新闻的触摸监听
	 * 
	 * @author ludaxu
	 * 
	 */
	class TopNewsTouchListener implements OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				mHandler.removeCallbacksAndMessages(null);// 删除handler中的消息回调

				break;
			case MotionEvent.ACTION_UP:
				mHandler.sendEmptyMessageDelayed(0, 3000);
				break;
			case MotionEvent.ACTION_CANCEL:
				mHandler.sendEmptyMessageDelayed(0, 3000);
				break;

			default:
				break;
			}
			return true;
		}

	}

	/**
	 * 新闻列表的适配器
	 * 
	 * @author ludaxu
	 * 
	 */
	class NewsAdapter extends BaseAdapter {

		private BitmapUtils utils;

		public NewsAdapter() {
			utils = new BitmapUtils(mActivity);
			utils.configDefaultLoadingImage(R.drawable.pic_item_list_default);
		}

		@Override
		public int getCount() {
			return mNewsList.size();
		}

		@Override
		public TabNewsData getItem(int position) {
			return mNewsList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = View.inflate(mActivity, R.layout.list_news_item,
						null);
				holder = new ViewHolder();
				holder.ivPic = (ImageView) convertView
						.findViewById(R.id.iv_pic);
				holder.tvTitle = (TextView) convertView
						.findViewById(R.id.tv_title);
				holder.tvDate = (TextView) convertView
						.findViewById(R.id.tv_date);
				convertView.setTag(holder);

			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			// 拿到新闻的对象
			TabNewsData item = getItem(position);
			holder.tvTitle.setText(item.title);
			holder.tvDate.setText(item.pubdate);
			utils.display(holder.ivPic, item.listimage);

			String ids = PrefUtils.getString(mActivity, "read_ids", "");
			if (ids.contains(getItem(position).id)) {
				holder.tvTitle.setTextColor(Color.RED);
			} else {
				holder.tvTitle.setTextColor(Color.BLACK);
			}
			return convertView;
		}

	}

	static class ViewHolder {
		public TextView tvTitle;
		public TextView tvDate;
		public ImageView ivPic;
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageSelected(int arg0) {
		TopNewsData topNewsData = mTopNewsList.get(arg0);
		tvTitle.setText(topNewsData.title);
	}

}
